// home/active/active-details.js
import api from '../../utils/api.js';
import network from '../../utils/network.js';
import formatDate from '../../utils/format_date';
import utils from '../../utils/utils';
import notice from '../../utils/notice.js';

const app = getApp();
let times = null;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        visibleLogin: false,
        visible: false,
        visibleOnline: false,
        submitTimeVisible: false,
        agree: false,
        details: {
          processType: 2,
          cover: "http://devhui.salonhui.com/assets/cover1.png",
          name: '遇见更好的自己—系列瑜伽公益课，快来报名吧！！遇见更好的自己—系列瑜伽公益课，快来报名吧！！遇见更好的自己—系列瑜伽公益课，快来报名吧！！',
          publishAvatar: '/assets/avator.png',
          publishName: '测试发布者',
          city: '武汉',
          poi: '绿地缤纷购物中心',
          bookingTimes: [
            {
              format: '2025.10.28 09:00-12:00',
              amount: 280,
              startTime: '2025.10.28 09:00',
              endTime: '2025.10.28 12:00'
            },
            {
              format: '2025.10.28 14:00-17:00',
              amount: 888
            }
          ],
          details: '“瑜”你成长 ‘伽’倍幸福瑜伽透过每一次柔软的呼吸身体和精神的纽带在体式中重新联结我们的肢愈加舒展心灵也愈加平和是意想不到的绝佳尝试',
          images: [
            "http://devhui.salonhui.com/assets/cover2.png",
            "http://devhui.salonhui.com/assets/cover1.png",
          ]
        },
        groupTimer: [
          {
            format2: '2024年8月10日 周六',
            res: [
              {
                timer: 1,
                disable: false,
              },
              {
                timer: 2,
                disable: false
              },
              {
                timer: 3,
                disable: true,
                disableText: '报'
              },
            ]
          },
          {
            format2: '2024年8月11日 周日',
            res: [
              {
                timer: 1,
                disable: false,
                disableText: '已满'
              },
              {
                timer: 2,
                disable: true
              },
              {
                timer: 3,
                disable: false
              }
            ]
          },
          {
            format2: '2024年8月12日 周一',
            res: [
              {
                timer: 1,
                disable: false,
                disableText: '已满'
              },
              {
                timer: 2,
                disable: false
              },
              {
                timer: 3,
                disable: true
              }
            ]
          }
        ],
        isSign: 0,
        myself: false,
        selectedTimerIds: [],
        count: 0,
        amount: 0,
        statusBarHeight: 0,
        isShare: false,
        userInfo: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // this.windowInfo = wx.getWindowInfo();
        // this.setData({
        //     statusBarHeight: this.windowInfo.statusBarHeight
        // })

        // if (options.isShare) {
        //     this.setData({
        //         isShare: options.isShare
        //     })
        // }

        // notice.addNotice("UserInfo", this.refreshUserInfo, this);
        // notice.addNotice("RefreshActiveTimer", this.refreshActiveTimer, this);
        // notice.addNotice("GetGroupTimer", this.getGroupTimer, this);

        // network.getJson(api.getActive, {
        //     id: options.id
        // }).then(res => {
        //     res.data.images = res.data.images.split(',');
        //     times = res.data.bookingTimes;
        //     for (let i = 0; i < times.length; i++) {
        //         times[i].startTemp = new Date(times[i].startTime).getTime();
        //     }
        //     times.sort((a, b) => a.startTemp - b.startTemp);
        //     for (let i = 0; i < times.length; i++) {
        //         times[i].format = formatDate.formatWeek(times[i].startTime, times[i].endTime);
        //         times[i].format2 = formatDate.formatWeek3(times[i].startTime);
        //         times[i].selected = false;

        //         // if (times[i].sumCount >= res.data.peopleNum) {
        //         //     times[i].disable = true;
        //         //     times[i].disableText = '已满';
        //         // }
        //     }

        //     app.getUserInfo().then(user => {
        //         this.setData({
        //             details: res.data,
        //             myself: res.data.creator == user.id,
        //             userInfo: user
        //         })

        //         this.name = user.name;
        //         this.mobile = user.mobile;
        //     })


        //     this.getGroupTimer();
        // })

        // wx.showShareMenu({
        //     withShareTicket: true,
        //     menus: ['shareAppMessage', 'shareTimeline']
        // })
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {
        // notice.removeNotice("UserInfo", this);
        // notice.removeNotice("RefreshActiveTimer", this);
        // notice.removeNotice("GetGroupTimer", this);
        // times = null;
    },

    onShareAppMessage() {
        let user = app.globalData.userInfo;
        return {
            title: this.data.details.name,
            imageUrl: this.data.details.images[0],
            path: `/home/active/active-details?id=${this.data.details.id}&parentId=${user.id}`
        }
    },
    // 下架
    delist () {
      const modal = this.selectComponent('#myModal');
      modal.show({
        type: 'confirm',
        message: '确定下架活动？',
        reason: "下架后，活动不对外显示",
      })
    },
    delistConfirm () {
      console.log('确认下架了');
    },
    homeTap() {
        wx.reLaunch({
            url: '/pages/active/active'
        })
    },

    backTap() {
        wx.navigateBack();
    },

    refreshUserInfo() {
        let userInfo = app.globalData.userInfo;
        this.setData({
            userInfo
        })
    },

    openSite(e) {
        wx.openLocation({
            name: this.data.details.poi,
            address: this.data.details.address,
            latitude: this.data.details.lat,
            longitude: this.data.details.lng,
            scale: 18
        })
    },

    getGroupTimer() {
        app.getUserInfo().then(user => {
            network.getJson(api.activePartTimes, {
                userId: user.id,
                activeId: this.data.details.id
            }).then(result => {
                let timers = result.data;
                for (let i = 0; i < times.length; i++) {
                    if (timers.indexOf(times[i].id) != -1) {
                        times[i].disable = true;
                    } else {
                        if (!times[i].disable) {
                            times[i].disable = false;
                        }
                    }
                    times[i].selected = false; // 初始未选中
                }
                this.setData({
                    groupTimer: utils.groupByData(times, 'format2')
                })
            })
        })
    },

    onShareTimeline() {
        let user = app.globalData.userInfo;
        return {
            title: this.data.details.name,
            imageUrl: this.data.details.images[0],
            path: `/home/active/active-details?id=${this.data.details.id}&parentId=${user.id}`
        }
    },

    callPhone(e) {
        wx.makePhoneCall({
            phoneNumber: this.data.details.publishPhone
        })
    },

    goEnroll() {
        if (this.data.details.processType == 1) {
          this.setData({
            submitTimeVisible: true
          })
        } else {
          this.setData({
            visibleOnline: true
          })
        }
        
        // if (app.globalData.userInfo.id == this.data.details.creator) {
        //     wx.showToast({
        //         icon: 'none',
        //         title: '本人发布的活动无需报名'
        //     })
        //     return;
        // }
        // if (app.globalData.userInfo.mobile) {
        //     if (this.data.details.processType == 1) {
        //         this.setData({
        //             visible: true
        //         });
        //     } else {
        //         this.setData({
        //             visibleOnline: true
        //         });
        //     }
        // } else {
        //     this.setData({
        //         visibleLogin: true
        //     });
        // }
    },

    onVisibleChangeLogin(e) {
        this.setData({
            visibleLogin: e.detail.visible,
        });
    },

    closeLoginTap() {
        this.setData({
            visibleLogin: false
        });
    },

    onVisibleOnlineChange(e) {
        this.setData({
            visibleOnline: e.detail.visible,
        });
    },

    agreeTap() {
        this.setData({
            agree: !this.data.agree
        })
    },

    getRealtimePhoneNumber(e) {
        this.closeLoginTap();
        if (e.detail.code) {
            network.getJson(api.getUserPhoneNumber, {
                userId: app.globalData.userInfo.id,
                code: e.detail.code
            }).then(res => {
                app.globalData.userInfo.mobile = res.data;
                return network.postJson(api.updateUser, app.globalData.userInfo)
            }).then(res => {
                wx.showToast({
                    title: '登录成功',
                })
            })
        }
    },

    onVisibleChange(e) {
        this.setData({
          submitTimeVisible: false,
        });
    },

    selectTimer(e) {
        if (e.detail.lastSelected) {
            this.data.selectedTimerIds.push(e.detail.lastId);
        } else {
            let idx = this.data.selectedTimerIds.indexOf(e.detail.lastId);
            if (idx != -1) {
                this.data.selectedTimerIds.splice(idx, 1);
            }
        }
        let count = 0;
        let amount = 0;
        for (let i = 0; i < this.data.details.bookingTimes.length; i++) {
            let index = this.data.selectedTimerIds.indexOf(this.data.details.bookingTimes[i].id);
            if (index != -1) {
                count += 1;
                amount += this.data.details.bookingTimes[i].amount * 100;
                this.data.details.bookingTimes[i].selected = true;
            } else {
                this.data.details.bookingTimes[i].selected = false;
            }
        }

        this.setData({
            count,
            amount: amount / 100
        })
    },

    submitTap() {
        let can = true;
        // for (let i = 0; i < this.data.details.bookingTimes.length; i++) {
        //     if (this.data.details.bookingTimes[i].selected) {
        //         can = true;
        //     }
        // }
        if (can) {
            wx.navigateTo({
                url: '/myself/enroll/enroll?active=' + encodeURIComponent(JSON.stringify(this.data.details))
            })
        } else {
            wx.showToast({
                icon: 'none',
                title: '请选择场次'
            })
        }
    },

    refreshActiveTimer(e) {
        console.log(e)
        this.setData({
            details: e,
            groupTimer: utils.groupByData(e.bookingTimes, 'format2')
        })

        this.data.selectedTimerIds = [];
        let count = 0;
        let amount = 0;
        for (let i = 0; i < this.data.details.bookingTimes.length; i++) {
            if (this.data.details.bookingTimes[i].selected) {
                count += 1;
                amount += this.data.details.bookingTimes[i].amount * 100;
                this.data.details.bookingTimes[i].selected = true;
                this.data.selectedTimerIds.push(this.data.details.bookingTimes[i].id);
            } else {
                this.data.details.bookingTimes[i].selected = false;
            }
        }

        this.setData({
            count,
            amount: amount / 100
        })
    },

    nameInput(e) {
        this.name = e.detail.value;
    },

    phoneInput(e) {
        this.mobile = e.detail.value;
    },

    enrollTap() {
        wx.reLaunch({
          url: '/home/success/success?mode=ENROLL_ONLINE&activeId=' ,
        })
        // network.postJson(api.activeOrderCreate, {
        //     activeId: this.data.details.id,
        //     publisherId: this.data.details.creator,
        //     userId: app.globalData.userInfo.id,
        //     username: this.name,
        //     phone: this.mobile,
        //     status: 1
        // }).then(res => {
        //     // wx.reLaunch({
        //     //     url: '/home/success/success?mode=ENROLL_ONLINE&groupCode=' + this.data.details.groupCode
        //     // })
        //     wx.reLaunch({
        //         url: '/active/group/group?groupCode=' + encodeURIComponent(this.data.details.groupCode)
        //     })
        // })
    },


    goRecordActive() {
        wx.navigateTo({
            url: '/myself/order/record-active?activeId=' + this.data.details.id
        })
    },
})